import { Input, NavBar, TextArea } from 'antd-mobile'

import styles from './index.module.scss'
import { useSelector } from 'react-redux'
import { useState, useRef, useEffect } from 'react'
import { RootState } from '@/types/store'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
type Props = {
  hideInput: () => void
  onUpdate: (key: string, value: string) => void
  type: '' | 'name' | 'intro'
}

const EditInput = ({ hideInput, type, onUpdate }: Props) => {
  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)

  const { userProfile } = useSelector((state: RootState) => state.profile)
  const [value, setValue] = useState(
    type === 'name' ? userProfile.name : userProfile.intro
  )

  useEffect(() => {
    if (type === 'name') {
      inputRef.current?.focus()
    } else {
      textRef.current?.focus()
      document.querySelector('textarea')?.setSelectionRange(-1, -1)
    }
  }, [type])
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        right={<span className="commit-btn" onClick={() => onUpdate(type, value)}>
          提交
        </span>}
        onBack={() => hideInput()}
      >
        编辑{type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>编辑{type === 'name' ? '昵称' : '简介'}</h3>

        {type === 'name'
          ? (
            <div className="input-wrap">
              <Input
                placeholder="请输入昵称"
                value={value}
                onChange={(e) => setValue(e)}
                maxLength={11}
                ref={inputRef}
              />
            </div>
            )
          : (
            <TextArea
              className="textarea"
              placeholder="请输入简介"
              showCount
              maxLength={99}
              value={value}
              onChange={(e) => setValue(e)}
              ref={textRef}
            />
            )}
      </div>
    </div>
  )
}

export default EditInput
